const {app, BrowserWindow, ipcMain, dialog} = require('electron')
const {SerialPort} = require('serialport')
const path = require('path')

const serial = require('./serial')

// 查询串口
async function listSerialPorts() {
    return await SerialPort.list().then((ports) => {
        return ports
    }).catch(err => {
        console.log(err)
    });
}

// 选择目标文件
async function chooseTargetFile() {
    const {canceled, filePaths} = await dialog.showOpenDialog();
    if (!canceled) {
        return filePaths[0]
    }
}

function createWindow() {
    const mainWindow = new BrowserWindow({
        webPreferences: {
            preload: path.join(__dirname, '../shared/preload.js')
        }
    })

    // 查询可用串口
    ipcMain.handle('serial:listSerialPorts', listSerialPorts);
    // 选择目标文件
    ipcMain.handle('serial:chooseTargetFile', chooseTargetFile);

    // 发送串口数据
    ipcMain.on('serial:sendSerialPortData', (event, serialConfig) => {
        return serial.sendSerialPortData(serialConfig);
    });

    mainWindow.loadFile('src/renderer/index.html')
    mainWindow.webContents.openDevTools()
}

app.whenReady().then(() => {
    createWindow()

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})
